#include "centralwidget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QDateTime>
#include <QMessageBox>
#include <QDebug>


CentralWidget::CentralWidget(QString port, QWidget *parent) :
    QWidget(parent)
{
    this->port = port.toInt();
    this->socket = new QUdpSocket(this);
    qDebug()<< this->port;
    if(!socket->bind(QHostAddress::LocalHost,this->port))
    {
        QMessageBox::information(this, "Error", "Port " + port + " already used!");
        exit(-1);
    }

    this->chat_history = new QListWidget(this);
    this->ip_text = new QLineEdit("192.168.211.69",this);
    this->port_text = new QLineEdit("777",this);
    this->message_text = new QLineEdit(this);
    this->send_button = new QPushButton("Send",this);

    QVBoxLayout * vl = new QVBoxLayout();
    vl->addWidget(new QLabel("Char history"));
    vl->addWidget(this->chat_history);

    vl->addWidget(new QLabel("Send to:"));
    QHBoxLayout * hl_ip_port = new QHBoxLayout();
    hl_ip_port->addWidget(new QLabel("IP"));
    hl_ip_port->addWidget(this->ip_text);
    hl_ip_port->addWidget(new QLabel("port"));
    hl_ip_port->addWidget(this->port_text);
    vl->addItem(hl_ip_port);

    vl->addWidget(new QLabel("Message text:"));
    QHBoxLayout * hl_message_send = new QHBoxLayout();
    hl_message_send->addWidget(this->message_text);
    hl_message_send->addWidget(this->send_button);
    vl->addItem(hl_message_send);

    setLayout(vl);

    connect(this->send_button, SIGNAL(clicked()), this, SLOT(send_message()));
    connect(this->message_text, SIGNAL(returnPressed()), this, SLOT(send_message()));

    connect(this->socket, SIGNAL(readyRead()), this, SLOT(get_message()));
}

void CentralWidget::send_message()
{
    QString str = this->message_text->text();
    this->message_text->setText("");

    QByteArray data;
    data.append("port " + QString::number(this->port) + " (" + QDateTime::currentDateTime().toString("dd.MM.yyyy HH:mm") + "): " + str);
    this->socket->writeDatagram(data, QHostAddress::LocalHost, this->port_text->text().toInt());

    str = "I (" + QDateTime::currentDateTime().toString("dd.MM.yyyy HH:mm") + "): " + str;

    this->chat_history->addItem(str);
}

void CentralWidget::get_message()
{
    QString str;
    while(this->socket->hasPendingDatagrams())
    {
        QByteArray data;
        data.resize(this->socket->pendingDatagramSize());
        this->socket->readDatagram(data.data(), this->socket->pendingDatagramSize());
        QString str_part(data);
        str += str_part;
    }

    this->chat_history->addItem(str);
}
